<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="学院代码" prop="collegeCode">
        <el-input
          v-model="queryParams.collegeCode"
          placeholder="请输入学院代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院名称" prop="collegeName">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="请输入学院名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学院地址" prop="collegeAddress">
        <el-input
          v-model="queryParams.collegeAddress"
          placeholder="请输入学院地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 修改研究生秘书的el-select部分 -->
      <el-form-item label="研究生秘书" prop="secretaryTeacherId">
        <el-select
          v-model="queryParams.secretaryTeacherId"
          placeholder="请输入教师姓名"
          clearable
          filterable
          remote
          :remote-method="filterTeachers"
          @change="handleTeacherChange"
          style="width: 200px;"
        >
          <el-option
            v-for="teacher in filteredTeachers"
            :key="teacher.uuid"
            :label="`${teacher.name} (${teacher.teacherCode})`"
            :value="teacher.uuid"
          >
            <span style="float: left">{{ teacher.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ teacher.teacherCode }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="院长" prop="deanTeacherId">
        <el-input
          v-model="queryParams.deanTeacherId"
          placeholder="请输入院长"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="院长" prop="deanTeacherId">
        <el-select
          v-model="queryParams.deanTeacherId"
          placeholder="请输入教师姓名"
          clearable
          filterable
          remote
          :remote-method="filterTeachers"
          @change="handleQuery"
          style="width: 200px;"
        >
          <el-option
            v-for="teacher in filteredTeachers"
            :key="teacher.uuid"
            :label="`${teacher.name} (${teacher.teacherCode})`"
            :value="teacher.uuid"
          >
            <span style="float: left">{{ teacher.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ teacher.teacherCode }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院成立日期" prop="establishmentDate">
        <el-date-picker clearable
          v-model="queryParams.establishmentDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择学院成立日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学院官网网址" prop="website">
        <el-input
          v-model="queryParams.website"
          placeholder="请输入学院官网网址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校区" prop="campus">
        <el-select v-model="queryParams.campus" placeholder="请选择校区" clearable style="width: 150px;">
          <el-option
            v-for="dict in campus_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['college:college:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['college:college:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['college:college:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['college:college:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="collegeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学院代码" align="center" prop="collegeCode" />
      <el-table-column label="学院名称" align="center" prop="collegeName" />
      <el-table-column label="学院地址" align="center" prop="collegeAddress" />
      <!-- <el-table-column label="研究生秘书" align="center" prop="secretaryTeacherId" /> -->
      <el-table-column label="研究生秘书" align="center" prop="secretaryTeacherId">
        <template #default="scope">
          <span>{{ getTeacherName(scope.row.secretaryTeacherId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="院长" align="center">
        <template #default="scope">
          <span>{{ getTeacherName(scope.row.deanTeacherId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学院成立日期" align="center" prop="establishmentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.establishmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学院官网网址" align="center" prop="website" />
      <el-table-column label="校区" align="center" prop="campus">
        <template #default="scope">
          <dict-tag :options="campus_type" :value="scope.row.campus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['college:college:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['college:college:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改学院信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="collegeRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学院代码" prop="collegeCode">
          <el-input v-model="form.collegeCode" placeholder="请输入学院代码" />
        </el-form-item>
        <el-form-item label="学院名称" prop="collegeName">
          <el-input v-model="form.collegeName" placeholder="请输入学院名称" />
        </el-form-item>
        <el-form-item label="学院地址" prop="collegeAddress">
          <el-input v-model="form.collegeAddress" placeholder="请输入学院地址" />
        </el-form-item>
        <!-- 修改对话框中的el-select -->
        <el-form-item label="研究生秘书" prop="secretaryTeacherId">
          <el-select
            v-model="form.secretaryTeacherId"
            placeholder="请输入教师姓名"
            clearable
            filterable
            remote
            :remote-method="filterTeachers"
            @change="handleTeacherChange"
            style="width: 100%;"
            :loading="loading"
          >
            <el-option
              v-for="teacher in filteredTeachers"
              :key="teacher.uuid"
              :label="`${teacher.name} (${teacher.teacherCode})`"
              :value="teacher.uuid"
            >
              <span style="float: left">{{ teacher.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ teacher.teacherCode }}
              </span>
            </el-option>
            <template #prefix>
              <span v-if="form._secretaryName">{{ form._secretaryName }}</span>
            </template>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="院长" prop="deanTeacherId">
          <el-input v-model="form.deanTeacherId" placeholder="请输入院长老师 ID" />
        </el-form-item> -->
        <el-form-item label="院长" prop="deanTeacherId">
          <el-select
            v-model="form.deanTeacherId"
            placeholder="请输入教师姓名"
            clearable
            filterable
            remote
            :remote-method="filterTeachers"
            style="width: 100%;"
            :loading="loading"
          >
            <el-option
              v-for="teacher in filteredTeachers"
              :key="teacher.uuid"
              :label="`${teacher.name} (${teacher.teacherCode})`"
              :value="teacher.uuid"
            >
              <span style="float: left">{{ teacher.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ teacher.teacherCode }}
              </span>
            </el-option>
            <template #prefix>
              <span v-if="form._deanName">{{ form._deanName }}</span>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="学院成立日期" prop="establishmentDate">
          <el-date-picker clearable
            v-model="form.establishmentDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择学院成立日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学院官网网址" prop="website">
          <el-input v-model="form.website" placeholder="请输入学院官网网址" />
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-select v-model="form.campus" placeholder="请选择校区">
            <el-option
              v-for="dict in campus_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="College">
import { listCollege, getCollege, delCollege, addCollege, updateCollege } from "@/api/college/college";
import { listTeacher} from "@/api/teacher/teacher";
import { loadAllParams } from "@/api/page";
import { debounce } from 'lodash-es';

const { proxy } = getCurrentInstance();
const { campus_type } = proxy.useDict('campus_type');

const collegeList = ref([]);
const open = ref(false);
// const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    collegeCode: null,
    collegeName: null,
    collegeAddress: null,
    secretaryTeacherId: null,
    deanTeacherId: null,
    establishmentDate: null,
    website: null,
    campus: null
  },
  rules: {
    collegeCode: [
      { required: true, message: "学院代码不能为空", trigger: "blur" }
    ],
    collegeName: [
      { required: true, message: "学院名称不能为空", trigger: "blur" }
    ],
    collegeAddress: [
      { required: true, message: "学院地址不能为空", trigger: "blur" }
    ],
    secretaryTeacherId: [
      { required: true, message: "请选择研究生秘书", trigger: "change" }
    ],
    deanTeacherId: [
      { required: true, message: "院长老师 ID不能为空", trigger: "blur" }
    ],
    campus: [
      { required: true, message: "校区不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学院信息管理列表 */
function getList() {
  loading.value = true;
  listCollege(queryParams.value).then(response => {
    collegeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    collegeId: null,
    collegeCode: null,
    collegeName: null,
    collegeAddress: null,
    secretaryTeacherId: null,
    deanTeacherId: null,
    establishmentDate: null,
    website: null,
    campus: null
  };
  proxy.resetForm("collegeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.collegeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学院信息管理";
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   const _collegeId = row.collegeId || ids.value
//   getCollege(_collegeId).then(response => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改学院信息管理";
//   });
// }
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  try {
    const res = await getCollege(row.collegeId);
    form.value = res.data;
    
    // 等待教师数据加载完成
    await getTeacherList();
    
    // 查找当前选中的教师信息
    if (res.data.secretaryTeacherId) {
      const selectedTeacher = teacherList.value.find(
        t => t.uuid === res.data.secretaryTeacherId
      );
      if (selectedTeacher) {
        // 显示教师姓名（仅用于展示，不存储到form）
        form.value._secretaryName = selectedTeacher.name;
      }
    }
    
    open.value = true;
    title.value = "修改学院信息管理";
  } catch (err) {
    console.error('获取详情失败:', err);
    proxy.$modal.msgError("数据加载失败");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["collegeRef"].validate(valid => {
    if (valid) {
      if (form.value.collegeId != null) {
        updateCollege(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCollege(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _collegeIds = row.collegeId || ids.value;
  proxy.$modal.confirm('是否确认删除学院信息管理编号为"' + _collegeIds + '"的数据项？').then(function() {
    return delCollege(_collegeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('college/college/export', {
    ...queryParams.value
  }, `college_${new Date().getTime()}.xlsx`)
}
// 在原有响应式数据部分添加
const teacherList = ref([]);
const filteredTeachers = ref([]);
// /** 查询教师信息 */
// const getTeacherList = async () => {
//   try {
//     const res = await listTeacher({ loadAllParams });
//     teacherList.value = res.rows;
//     filteredTeachers.value = res.rows;
//   } catch (err) {
//     console.error('教师数据加载失败:', err);
//     proxy.$modal.msgError("教师数据加载失败");
//   }
// };
// 修改后的教师数据加载方法
const getTeacherList = async () => {
  try {
    if (teacherList.value.length === 0) { // 避免重复加载
      const res = await listTeacher({ loadAllParams });
      teacherList.value = res.rows;
      filteredTeachers.value = res.rows;
    }
  } catch (err) {
    console.error('教师数据加载失败:', err);
    proxy.$modal.msgError("教师列表加载失败");
  }
};

/** 过滤教师（带防抖） */
// const filterTeachers = debounce((query) => {
//   if (!teacherList.value) return;
  
//   if (query) {
//     const lowerQuery = query.trim().toLowerCase();
//     filteredTeachers.value = teacherList.value.filter(teacher =>
//       teacher.name?.toLowerCase().includes(lowerQuery) || 
//       teacher.teacherCode?.toLowerCase().includes(lowerQuery)
//     );
//   } else {
//     filteredTeachers.value = teacherList.value;
//   }
// }, 300);
// 在响应式数据部分添加
const loading = ref(false);

// 修改过滤方法
const filterTeachers = debounce(async (query) => {
  loading.value = true;
  try {
    if (query) {
      const lowerQuery = query.trim().toLowerCase();
      filteredTeachers.value = teacherList.value.filter(teacher => 
        teacher.name?.toLowerCase().includes(lowerQuery) ||
        teacher.teacherCode?.includes(query)
      );
    } else {
      filteredTeachers.value = teacherList.value;
    }
  } finally {
    loading.value = false;
  }
}, 300);
// 获取教师姓名的方法
function getTeacherName(uuid) {
  if (!uuid) return '-';
  const teacher = teacherList.value.find(t => t.uuid === uuid);
  return teacher ? `${teacher.name} (${teacher.teacherCode})` : '未知教师';
}

// 在onMounted或初始化时调用
// onMounted(() => {
//   getTeacherList();
//   getList(); // 保留原有的学院数据加载
// });
onMounted(async () => {
  await getTeacherList(); // 确保先加载教师数据
  getList(); // 然后加载学院数据
});
getTeacherList();
getList();
</script>
